package com.landiao.core.job;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.landiao.common.Constant;
import com.landiao.common.weixin.WxConsts;
import com.landiao.common.weixin.WxErrorException;
import com.landiao.common.weixin.WxMpService;
import com.landiao.common.weixin.bean.WxMpCustomMessage;
import com.landiao.common.weixin.bean.WxMpMassOpenIdsMessage;
import com.landiao.common.weixin.bean.WxMpMassSendResult;
import com.landiao.entities.Material;
import com.landiao.entities.Vip;
import com.landiao.service.MaterialService;
import com.landiao.service.VipService;

/**
 * 功能说明:定时器
 * 
 */
@Component("serverJob")
public class ServerJob {

	private static final Logger L = LoggerFactory.getLogger(ServerJob.class);

	@Autowired
	@Qualifier("vipWxService")
	private WxMpService vipWxService;

	@Autowired
	private VipService vipService;

	@Autowired
	private MaterialService materialService;

	/**
	 * 定时发送生日关怀
	 */
	public void sendBirthdayConcern() {
		L.info("定时发送生日关怀");
		Material material = new Material();
		material.setCompId(Constant.comp.getCompId());
		material.setPurpose("SRGH");
		Material result = materialService.getByPurpose(material);
		if(result == null)
			return;
		List<Vip> list = this.vipService.getByBirthday();
		if(list!=null&&list.size()>0){
			List<String> operidList = new ArrayList<>();
			for(Vip vip:list){
				if(StringUtils.isNotEmpty(vip.getOperId()))
					operidList.add(vip.getOperId());
			}
			if(operidList.size()==0)
				return;
			if(operidList.size()==1){
				WxMpCustomMessage message = new WxMpCustomMessage();
				message.setMediaId(result.getMediaId());
				message.setMsgType(WxConsts.MASS_MSG_IMAGE);
				message.setTouser(operidList.get(0));
				try {
					vipWxService.customMessageSend(message);
				} catch (WxErrorException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				WxMpMassOpenIdsMessage message = new WxMpMassOpenIdsMessage();
				message.setMediaId(result.getMediaId());
				message.setMsgType(WxConsts.MASS_MSG_IMAGE);
				message.setTouser(operidList);
				try {
					WxMpMassSendResult sendResult = vipWxService.massOpenIdsMessageSend(message);
					L.debug(sendResult.toString());
				} catch (WxErrorException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
